/**
 * tree结构方法
 */
import { isEmpty } from 'lodash'
import { toRaw } from 'vue'
import { TagNode } from '../interface/node'

interface Options {
  activeList: string[]
  blackSizeList: string[]
}

/**
 * 树结构的数据添加一些常用字段
 * @param data
 * @param options
 */
export const addFields = (data: TagNode[], options?: Partial<Options>) => {
  let level: any = 0
  const { activeList, blackSizeList } = options || {}
  const hasActive = activeList?.length
  data.forEach((i: TagNode) => {
    i.level = 1
    i.children?.forEach((i: TagNode) => (i.twoLevel = true))
  })
  // let parent: any = null
  const each = (param: TagNode[]) => {
    level += 1
    param.forEach((i: TagNode, index) => {
      if (hasActive && activeList.includes(i._id || '')) {
        i.active = true
      }
      i.size = 53
      if (blackSizeList?.length && !blackSizeList?.includes(i._id || '')) {
        i.size = 0
      }
      if (i.twoLevel) {
        level = 2
      }
      if (!i.level) {
        i.level = level
      }
      i.editName = i.name
      if (i.children?.every((i: TagNode) => isEmpty(i.children))) {
        i.children.forEach((m: TagNode) => {
          m.isLeaf = true
        })
      }
      if (isEmpty(i.children)) {
        i.isLeaf = true
      }
      if (!i.isLeaf && i.children && i.children[0] && !hasActive) {
        i.children[0].active = true
      }
      if (i.level === 1 && index === 0 && !hasActive) {
        i.active = true
      }
      if (i.children) {
        each(i.children)
      }
    })
  }
  each(data)
}

export const deepToRaw: any = (tree: TagNode[]) => {
  return tree.map((i: TagNode) => ({
    ...toRaw(i),
    children: !isEmpty(i.children) ? deepToRaw(i.children || []) : i.children
  }))
}
